package org.stvd.controller.admin;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.DateUtil;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.common.CodeTable;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.common.CodeTableService;
import org.stvd.service.common.CommonService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 系统机构-控制类
 * @author houzx
 */
@Api(tags = "系统机构接口")
@Controller
@RequestMapping("/admin/department")
public class DepartmentController extends BaseController {

    @Autowired
    DepartmentService departmentService;
    @Autowired
    CodeTableService codeTableService;
    @Autowired
    private GuidsService guidsService;
    @Autowired
    private CommonService commonService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/department/";

    /**
     * 机构管理请求
     * @param department
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "management")
    public String onPageLoad(@ModelAttribute("department") Department department) {
        if(!StringUtil.isEmpty(request.getParameter("gid"))) {
            department.setGuid(request.getParameter("gid"));
        }
        if(StringUtil.isEmpty(department.getGuid())) {
            department.setGuid(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid);
        }
        loadDepartmentResource(department);
        return tmpURL + "DepartmentManagement.html";
    }
    
    @ApiIgnore
    @PostMapping(value = "management")
    public String onPageLoadAction(@ModelAttribute("department") Department department) {
        loadDepartmentResource(department);
        return tmpURL + "DepartmentManagement.html";
    }

    // 加载机构资源信息公共方法
    private void loadDepartmentResource(Department department) {
        map.put("guidsList", guidsService.listGuidByUserId(SecurityUserHolder.getCurrentUserId()));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
        map.put("depList", queryDepByGuid(department.getGuid()));
        map.put("dep", SecurityUserHolder.getCurrentMaxAuthDep(department.getGuid()));
    }
    
    /**
     * 新增机构信息GET请求
     * @param guid
     * @param department
     */
    @ApiIgnore
    @GetMapping(value = "add/{guid}")
    public String onAddLoad(@PathVariable String guid, 
        @ModelAttribute("department") Department department) {
        String provID = (department.getProvinceNo().length() == 6) ? department.getProvinceNo().substring(0, 2) : "000000";
        String cityID = (department.getCityNo().length() == 6) ? department.getCityNo().substring(0, 4) : "000000";
        try {
            // 加载省、市、县区
            List<CodeTable> listAll = codeTableService.findAll("dic_native_place");
            map.put("listPro", codeTableService.getCodeTableListByRegExp(listAll, "^[0-9]{2}0000$"));
            map.put("listCity", codeTableService.getCodeTableListByRegExp(listAll, "^" + provID + "[0-9][1-9]00$"));
            map.put("listRegin", codeTableService.getCodeTableListByRegExp(listAll, "^" + cityID + "[0-9][1-9]$"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 加载机构列表
        map.put("depList", queryDepByGuid(guid));
        map.put("dep", SecurityUserHolder.getCurrentMaxAuthDep(guid));
        map.put("guid", guid);
        return tmpURL + "DepartmentAdd.html";
    }

    @ApiOperation(value = "新增机构信息")
    @Log(title = "新增机构信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onAddAction(
        @Valid @ModelAttribute("department") Department department,  BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        department.setInnerCode(StringUtil.formatStrLen(department.getDepCode(), 10));
        if (!department.getUpperId().equals("-1")) {
            Department upperDep = departmentService.findByPk(Department.class, department.getUpperId());
            if (upperDep != null) {
                department.setInnerCode(upperDep.getInnerCode() + StringUtil.formatStrLen(department.getDepCode(), 10));
            }
        }
        department.setDepId(StringUtil.getRandomUUID());
        department.setInputDate(DateUtil.getSystemDate());
        department.setOperator(SecurityUserHolder.getCurrentUserId());
        department.setStatus("T");
        departmentService.insert(department);

        map.clear();
        result.setMsg("新增成功！");
        return result;
    }

    /**
     * 修改机构信息请求
     * @param depId
     */
    @ApiIgnore
    @GetMapping(value = "edit/{depId}")
    public String onEditLoad(@PathVariable String depId) throws Exception {
        Department department = departmentService.findByPk(Department.class, depId);
        if(department!=null) {
            if (department.getAreaNo().length() == 6) {
                department.setProvinceNo(department.getAreaNo().substring(0, 2) + "0000");
                department.setCityNo(department.getAreaNo().substring(0, 4) + "00");
                department.setRegionNo(department.getAreaNo());
            } else {
                department.setProvinceNo("000000");
                department.setCityNo("000000");
                department.setRegionNo("000000");
            }
    
            List<CodeTable> listAll = codeTableService.findAll("dic_native_place");
            String provID = (department.getProvinceNo().length() == 6) ? department.getProvinceNo().substring(0, 2) : "000000";
            String cityID = (department.getCityNo().length() == 6) ? department.getCityNo().substring(0, 4) : "000000";
            // 加载省、市、县区
            map.put("listPro", codeTableService.getCodeTableListByRegExp(listAll, "^[0-9]{2}0000$"));
            map.put("listCity", codeTableService.getCodeTableListByRegExp(listAll, "^" + provID + "[0-9][1-9]00$"));
            map.put("listRegin", codeTableService.getCodeTableListByRegExp(listAll, "^" + cityID + "[0-9][1-9]$"));
            // 加载机构列表
            map.put("department", department);
            map.put("depList", queryDepByGuid(department.getGuid()));
            map.put("dep", SecurityUserHolder.getCurrentMaxAuthDep(department.getGuid()));
        }
        return tmpURL + "DepartmentEdit.html";
    }

    @ApiOperation(value = "修改机构信息")
    @Log(title = "修改机构信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditAction(
        @Valid @ModelAttribute("department") Department department, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        if (department.getDepId().equals(department.getUpperId())
                || departmentService.isChildDepartment(department.getDepId(), department.getUpperId(), department.getGuid())) {
            result.setError("上级机构不能是当前机构或下属机构！");
            return result;
        }
        String innerCode = StringUtil.formatStrLen(department.getDepCode(), 10);
        String originInnerCode = department.getInnerCode();
        department.setInnerCode(innerCode);
        if (!department.getUpperId().equals("-1")) {
            Department upperDep = departmentService.findByPk(Department.class, department.getUpperId());
            if (upperDep != null) {
                innerCode = upperDep.getInnerCode() + innerCode;
                department.setInnerCode(innerCode);
            }
        }
        department.setInputDate(DateUtil.getSystemDate());
        department.setOperator(SecurityUserHolder.getCurrentUserId());
        departmentService.update(department);

        //更新子机构的innerCode
        for (Department depChild : departmentService.findDepartmentByInnerCode(originInnerCode, department.getGuid())) {
            if (!depChild.getDepId().equals(department.getDepId())) {
                depChild.setInnerCode(depChild.getInnerCode().replaceFirst(originInnerCode, innerCode));
                departmentService.update(depChild);
            }
        }

        map.clear();
        result.setMsg("修改成功！");
        return result;
    }

    /**
     * 机构信息删除
     * @param guid
     * @param depId
     * @param depName
     */
    @ApiOperation(value = "删除机构信息")
    @Log(title = "删除机构信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onDelete(String guid, String depId, String depName) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            departmentService.deleteDepartment(depId, guid);
            result.setMsg("机构‘" + depName + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除机构‘" + depName + "’失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
    
    /*
     * 根据平台GUID获取权限机构列表
     */
    @ApiOperation(value = "获取权限机构列表")
    @PostMapping(value = "queryall")
    @ResponseBody
    public List<Department> queryDepByGuid(String guid) {
        boolean isManage = commonService.checkManage(SecurityUserHolder.getCurrentUserId(), guid);
        if(isManage) {
            return departmentService.getFormatAllDepByGuid(guid);
        }else{
            return departmentService.getFormatChildDepartment(SecurityUserHolder.getCurrentMaxAuthDepId(guid), guid);
        }
    }
}
